from django.shortcuts import render
from .models import WebConfig, VisitNumber, Article, Category
from django.views.generic.base import View
from utils.VisitCount import change_info
from pure_pagination import Paginator, PageNotAnInteger


# Create your views here.

class IndexView(View):
    def get(self, request, *args, **kwargs):
        all_articles = Article.objects.all()
        # 获取访问ip
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            ip = request.META.get("HTTP_X_FORWARDED_FOR")
        else:
            ip = request.META.get("REMOTE_ADDR")
        change_info(request)
        # 获取网站配置信息
        web_config = WebConfig.objects.all()[0]
        # 统计访问总数
        visit_total = VisitNumber.objects.all()[0].count
        # 查询某个分类的文章
        article_category_id = request.GET.get('article_category_id', '没有获取到文章分类id')
        if article_category_id == '':
            # 获取所有文章，并按发布时间排序
            all_articles = all_articles.order_by('-created_time')
        elif article_category_id == '1':
            all_articles = all_articles.filter(category_id=1)
        elif article_category_id == '2':
            all_articles = all_articles.filter(category_id=2)
        elif article_category_id == '3':
            all_articles = all_articles.filter(category_id=3)
        elif article_category_id == '4':
            all_articles = all_articles.filter(category_id=4)
        elif article_category_id == '6':
            all_articles = all_articles.filter(category_id=6)
        # 统计文章总数
        article_total = all_articles.count()
        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
            # 第二个参数代表每一页显示的个数
        p = Paginator(all_articles, 1, request=request)
        article_page = p.page(page)
        return render(request, 'index.html', locals())
